Skip to content

Conversation

@gjohansson-ST
Copy link
Member

@gjohansson-ST gjohansson-ST commented Nov 3, 2024

Proposed change

Clarify the rules regarding additional state attributes as decided in home-assistant/architecture#680

Type of change

  • Document existing features within Home Assistant
  • Document new or changing features which there is an existing pull request elsewhere
  • Spelling or grammatical corrections, or rewording for improved clarity
  • Changes to the backend of this documentation
  • Removed stale or deprecated documentation

Additional information

  • This PR fixes or closes issue: fixes #
  • Link to relevant existing code or pull request:

Summary by CodeRabbit

  • Documentation
    • Added a new "State attributes" section explaining how entities can expose extra state attributes, expected/unsupported values, handling of None, and guidance on when to use attributes versus separate sensors, with examples. Note: the section currently appears twice in the documentation. (Documentation-only change.)

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 3, 2024

📝 Walkthrough

Walkthrough

Adds documentation to docs/core/entity.md describing extra_state_attributes (state attributes), rules for attribute values and None, guidance on when to use attributes versus separate sensors, and notes that the new section was inserted twice in the Advanced properties area. No code changes.

Changes

Cohort / File(s) Change summary
Documentation: entity doc
docs/core/entity.md
Added new "State attributes" sections describing extra_state_attributes, expected attribute rules (including handling None), guidance on when to use attributes vs separate sensors, and notes about attribute expectations. The content appears duplicated within the Advanced properties area. No functional/code changes.

Sequence Diagram(s)

No sequence diagram — documentation-only changes that do not alter control flow.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Potential review focus:

  • Confirm whether the duplicated "State attributes" section is intentional; remove one copy if accidental.
  • Validate clarity and accuracy of rules for None/unsupported attribute values and the guidance on when to use separate sensors.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The pull request title "Clarify state attributes rules for entity" is directly related to the main change in the changeset. According to the raw summary, the PR adds a new "State attributes" section to the documentation describing how entities can provide extra state attributes and the rules governing them. The title accurately and concisely summarizes this primary change, making it clear to reviewers scanning the history that the PR focuses on documenting state attributes guidance. The title is specific and meaningful without unnecessary noise or vague language.
Description Check ✅ Passed The pull request description includes the two main required sections: "Proposed change" is filled with clear context referencing an architecture discussion, and "Type of change" has the appropriate box checked for documenting existing features. However, the description is missing the entire "Checklist" section that should verify compliance with documentation guidelines and testing, and the "Additional information" section fields are not completed. Despite these structural gaps, the core information necessary to understand the PR's purpose and scope is communicated effectively, meeting the threshold of being mostly complete with the essential content present.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch gj-20241103-1

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
docs/core/entity.md (2)

122-132: Fix grammar and consider adding a code example.

  1. There's a grammatical error in the text. Please fix:
-If an attributes is not expected
+If an attribute is not expected
  1. Consider adding a code example to illustrate these rules. For instance:
class MyEntity(Entity):
    @property
    def extra_state_attributes(self):
        """Return entity specific state attributes."""
        attributes = {
            "expected_attribute": self._value or None,  # Always present
            "configuration_dependent": "value"  # Only when configured
        }
        return attributes
🧰 Tools
🪛 LanguageTool

[grammar] ~131-~131: The plural noun “attributes” cannot be used with the article “an”. Did you mean “an attribute” or “attributes”?
Context: ...None` and remain in the dictionary - If an attributes is not expected, it should not be in th...

(A_NNS)


Line range hint 134-139: Consider enhancing the System properties documentation.

The section could be more helpful with additional context:

  1. Add a note explaining that these properties are managed through the entity registry.
  2. Add a warning about not implementing custom logic for these properties, as they are system-managed.

Example addition:

:::warning
These properties are managed by Home Assistant through the entity registry. Integrations should not implement custom logic for these properties as it may conflict with system behavior.
:::
🧰 Tools
🪛 LanguageTool

[grammar] ~131-~131: The plural noun “attributes” cannot be used with the article “an”. Did you mean “an attribute” or “attributes”?
Context: ...None` and remain in the dictionary - If an attributes is not expected, it should not be in th...

(A_NNS)

🪛 Markdownlint

120-120: Expected: 4; Actual: 3; Too few cells, row will be missing data
Table column count

(MD056, table-column-count)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4bd68db and ec175df.

📒 Files selected for processing (1)
  • docs/core/entity.md (1 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/core/entity.md

[grammar] ~131-~131: The plural noun “attributes” cannot be used with the article “an”. Did you mean “an attribute” or “attributes”?
Context: ...None` and remain in the dictionary - If an attributes is not expected, it should not be in th...

(A_NNS)

🔇 Additional comments (1)
docs/core/entity.md (1)

Line range hint 1-1000: Overall documentation changes look good!

The additions effectively clarify the rules for state attributes and system properties, which aligns well with the PR objectives. The document maintains good structure and readability.

🧰 Tools
🪛 LanguageTool

[grammar] ~131-~131: The plural noun “attributes” cannot be used with the article “an”. Did you mean “an attribute” or “attributes”?
Context: ...None` and remain in the dictionary - If an attributes is not expected, it should not be in th...

(A_NNS)

🪛 Markdownlint

120-120: Expected: 4; Actual: 3; Too few cells, row will be missing data
Table column count

(MD056, table-column-count)

@home-assistant home-assistant bot marked this pull request as draft November 4, 2024 10:53
@home-assistant
Copy link

home-assistant bot commented Nov 4, 2024

Please take a look at the requested changes, and use the Ready for review button when you are done, thanks 👍

Learn more about our pull request process.

@gjohansson-ST gjohansson-ST marked this pull request as ready for review November 9, 2024 21:25
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
docs/core/entity.md (2)

122-132: Enhance the state attributes section with examples

While the rules are clear, adding concrete examples would help developers better understand when attributes should be included or excluded from the dictionary. Consider adding examples for:

  1. Expected attributes (e.g., supported features)
  2. Attributes that should be None
  3. Attributes that should not be in the dictionary

Here's a suggested addition after line 132:

- If an attribute is not expected, it should not be in the dictionary. An attribute is expected if supported by the entity, for example as indicated by `supported_features`.
+ If an attribute is not expected, it should not be in the dictionary. An attribute is expected if supported by the entity, for example as indicated by `supported_features`.
+
+ ### Examples
+
+ ```python
+ @property
+ def extra_state_attributes(self):
+     """Return entity specific state attributes."""
+     attributes = {}
+     
+     # Example 1: Expected attribute based on supported features
+     if self._attr_supported_features & SUPPORT_BRIGHTNESS:
+         attributes["brightness"] = self._brightness
+     
+     # Example 2: Expected attribute that might be None
+     if self._attr_supported_features & SUPPORT_COLOR:
+         attributes["rgb_color"] = self._rgb_color  # Could be None
+     
+     # Example 3: Conditional attribute that should not be included
+     # Don't do this:
+     # if self._is_dimmable:
+     #     attributes["brightness"] = self._brightness
+     
+     return attributes
+ ```

Line range hint 143-401: LGTM with a minor suggestion

The updated sections on entity naming and property implementation are clear and well-documented. The examples effectively demonstrate best practices. Consider adding a note about error handling in the property implementation example to make it more complete.

Add error handling to the example:

     def update(self) -> None:
         """Update entity state."""
         try:
             self._device.update()
-        except ExampleException:
+        except ExampleException as ex:
             if self.available:  # Read current state, no need to prefix with _attr_
-                LOGGER.warning("Update failed for %s", self.entity_id)
+                LOGGER.warning("Update failed for %s: %s", self.entity_id, str(ex))
             self._attr_available = False  # Set property value
             return
+        except Exception as ex:
+            LOGGER.error("Unexpected error updating %s: %s", self.entity_id, str(ex))
+            self._attr_available = False
+            return
🧰 Tools
🪛 Markdownlint

120-120: Expected: 4; Actual: 3; Too few cells, row will be missing data
Table column count

(MD056, table-column-count)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ec175df and eabb8aa.

📒 Files selected for processing (1)
  • docs/core/entity.md (1 hunks)
🔇 Additional comments (1)
docs/core/entity.md (1)

Line range hint 134-141: LGTM!

The new "System properties" section clearly explains that these properties are controlled by Home Assistant and should not be overridden by integrations. The documentation for the enabled property is accurate and helpful.

🧰 Tools
🪛 Markdownlint

120-120: Expected: 4; Actual: 3; Too few cells, row will be missing data
Table column count

(MD056, table-column-count)

Comment on lines 122 to 129
## State attributes

Entities can provide additional state attributes besides the built-in ones, to provide further details to its state.
This should be done by providing a dictionary with keys and values to the `extra_state_attributes` property.

Providing state attributes comes with the following rules:

- If an attribute is expected, it should be in the dictionary. Attributes should not "come and go".
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we also indicate our rules for what belongs in state attributes and what should be separate entities and what should be action calls?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that would probably be good although do we really have clear rules?
I think we could do that in a follow-up in that case.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Frenck once mentioned this in the members channel

Some helpful guidance with that, that I apply (for myself)

  • Would someone extract it using a template into an other (binary) sensor -> Not an attribute
  • It is essential to automation on? Can it be standalone as its own entity? -> Not an attribute
  • It is static, e.g., from configuration; doesn't belong in the state machine -> Not an attribute
  • Do we want to track long term stats of the value? -> Not an attribute

Additionally:

  • Does is have historical value? If not, exlude it from being recorded.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that makes sense but I'm not sure we can classify it as rules?
Maybe as "guidelines"?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh right. I think that if we are going to talk about state attributes, that we also explain that we are picky in what we want using these guidelines :)


- If an attribute is expected, it should be in the dictionary. Attributes should not "come and go".
- If an attribute is expected, but it's not providing a value right now, its value should be `None` and remain in the dictionary.
- If an attribute is not expected, it should not be in the dictionary. An attribute is expected if supported by the entity, for example as indicated by `supported_features`.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not really sure what this means and how it would look in practice

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As an example, in statistics the buffer_usage_ratio attribute is only shown if the sensor is configured to handle a buffer size. Otherwise this attribute would be irrelevant hence not showing in that case.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But how can someone expect it to be there? We're quite bad with describing entities in the docs, let alone describing the state attributes

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the developer docs not the user docs. The attribute is expected if it's part of a supported feature and that feature is supported or if it's an extra state attribute the attribute is expected if the device has support for that attribute.

Providing state attributes comes with the following rules:

- If an attribute is expected, it should be in the dictionary. Attributes should not "come and go".
- If an attribute is expected, but it's not providing a value right now, its value should be `None` and remain in the dictionary.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the first 2 rules are quite similar. I also think we should explain what happens when for example the entity is unavailable. What should we do then?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could perhaps combine the first two as they talk about the same thing.
I'm not sure what you mean by unavailable? Should there be any special consideration for it?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If an entity is unavailable, does it still read the extra state attributes property when writing state? And if so, should everything be set to None?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

State attributes are only set if the state of the entity is not unavailable. This is part of the base entity logic. Integrations should not adjust any logic concerning availability and state attributes.

@frenck
Copy link
Member

frenck commented Sep 4, 2025

@gjohansson-ST Should we move this forward?

@gjohansson-ST
Copy link
Member Author

Yes, I'll try to rewrite from the feedback shortly so we can merge it in.

@silamon silamon marked this pull request as draft September 12, 2025 18:23
@gjohansson-ST gjohansson-ST marked this pull request as ready for review October 24, 2025 21:49
@gjohansson-ST
Copy link
Member Author

Took a little bit of time but it's now rewritten according to the feedback so far.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between eabb8aa and 88c0f52.

📒 Files selected for processing (1)
  • docs/core/entity.md (1 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/core/entity.md

[grammar] ~139-~139: Use a hyphen to join words.
Context: ...an attribute. - Do we want to track long term statistics of the value? -> Not an ...

(QB_NEW_EN_HYPHEN)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Redirect rules - developers-home-assistant
  • GitHub Check: Header rules - developers-home-assistant
  • GitHub Check: Pages changed - developers-home-assistant
🔇 Additional comments (1)
docs/core/entity.md (1)

122-130: Verify content aligns with prior architectural feedback.

The new section appropriately addresses prior review feedback by clarifying that rules apply to all state attributes, including the supported_features example for determining expected attributes. The guidelines section (lines 134–140) incorporates the decision criteria suggested in earlier reviews.

One minor observation: Line 124 reads "to provide further details to its state"—the past review suggested "to provide further details of its state" but your wording is acceptable and natural. No change needed here.

Verify that the placement of this new section doesn't create any structural issues in the rendered documentation and that the guidelines provide sufficient clarity without needing inline examples.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 88c0f52 and e51f55a.

📒 Files selected for processing (1)
  • docs/core/entity.md (1 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/core/entity.md

[grammar] ~139-~139: Use a hyphen to join words.
Context: ...an attribute. - Do we want to track long term statistics of the value? -> Not an ...

(QB_NEW_EN_HYPHEN)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Redirect rules - developers-home-assistant
  • GitHub Check: Header rules - developers-home-assistant
  • GitHub Check: Pages changed - developers-home-assistant
🔇 Additional comments (1)
docs/core/entity.md (1)

122-140: Duplication has been resolved—"State attributes" section appears only once.

The verification confirms there is exactly one "## State attributes" section header in docs/core/entity.md. The section is not duplicated, and the provided code snippet accurately represents the current state of the document.

Comment on lines +122 to +140
## State attributes

Entities can provide additional state attributes besides the built-in ones, to provide further details to its state.
This should be done by providing a dictionary with keys and values to the `extra_state_attributes` property.

Providing state attributes comes with the following rules:

- If an attribute is expected, it should be in the dictionary. Attributes should not "come and go". If it's not currently providing a value it should set it to `None`.
- If an attribute is not expected, it should not be in the dictionary. An attribute is expected if supported by the entity, for example as indicated by `supported_features`.

Most often, the use of state attributes should be limited and in general it's often better to use another sensor than providing data as attributes.

Some general guidance to consider how to handle it:

- Would someone extract it using a template into an other (binary) sensor -> Not an attribute.
- It is essential to automation on? Can it be standalone as its own entity? -> Not an attribute.
- It is static, e.g., from configuration; doesn't belong in the state machine -> Not an attribute.
- Do we want to track long term statistics of the value? -> Not an attribute.
- Does it have historical value? If not, it can be an attribute and exclude it from being recorded.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Content is well-structured and addresses the architecture decision. The new "State attributes" section clearly establishes rules and provides actionable guidance. However, there are several grammar and phrasing issues that need correction.

Apply the following diffs to fix grammar and phrasing issues:

- Would someone extract it using a template into an other (binary) sensor -> Not an attribute.
+ Would someone extract it using a template into another (binary) sensor -> Not an attribute.
- It is essential to automation on? Can it be standalone as its own entity? -> Not an attribute.
+ Is it essential to automation? Can it be standalone as its own entity? -> Not an attribute.
- Do we want to track long term statistics of the value? -> Not an attribute.
+ Do we want to track long-term statistics of the value? -> Not an attribute.
- Does it have historical value? If not, it can be an attribute and exclude it from being recorded.
+ Does it have historical value? If not, it can be an attribute; exclude it from being recorded.
🧰 Tools
🪛 LanguageTool

[grammar] ~139-~139: Use a hyphen to join words.
Context: ...an attribute. - Do we want to track long term statistics of the value? -> Not an ...

(QB_NEW_EN_HYPHEN)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants